//
//  ADModule.m
//  CreateWithSuper
//
//  Created by chenjunbo on 2024/5/18.
//

@import GoogleMobileAds;

#import "ADModule.h"
#import "CSNetworkHelper.h"
#import "CSFullNavVC.h"

@interface ADModule()<GADFullScreenContentDelegate,GADNativeAdLoaderDelegate, GADAdLoaderDelegate,GADNativeAdDelegate>

@property (nonatomic, strong) GADInterstitialAd *interAd;
@property (nonatomic, assign) bool interIsLoading;

@property (nonatomic, strong) GADAppOpenAd *openAd;
@property (nonatomic, assign) bool openIsLoading;

@property (nonatomic, strong) GADAdLoader *navLoadAd;
@property (nonatomic, strong) GADNativeAd *navAd;
@property (nonatomic, strong) GADNativeAdView *nativeAdView;
@property (nonatomic, assign) bool navIsLoading;

@property (nonatomic, strong) NSString *intADStr;
@property (nonatomic, strong) NSString *openADStr;
@property (nonatomic, strong) NSString *navADStr;

@end

@implementation ADModule

+ (instancetype)standardInstance {
    static ADModule *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)getAdStr{
    NSMutableArray *dataArr = [NSMutableArray arrayWithArray:self.dataDict[@"adCfgs"]];
    
    [dataArr enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj[@"adPlace"] isEqualToString:@"start"]){
            self.openADStr = obj[@"adSource"][0][@"placeId"];
        }
        if ([obj[@"adPlace"] isEqualToString:@"finish"]){
            self.intADStr = obj[@"adSource"][0][@"placeId"];
            
            if ([obj[@"adSource"][0][@"type"] isEqualToString:@"nav"]){
                self.showIntOrNav = YES;
            }
            
        }
        if ([obj[@"adPlace"] isEqualToString:@"home"]){
            self.navADStr = obj[@"adSource"][0][@"placeId"];
        }
    }];
    
}

- (void)requestNavAd{
    
    if (self.navAd){
        NSLog(@"原生广告:已经存在");
        return;
    }
    
    if (self.navIsLoading){
        NSLog(@"原生广告:正在加载中");
        return;;
    }
    
    GADMultipleAdsAdLoaderOptions *multipleAdsOptions = [[GADMultipleAdsAdLoaderOptions alloc] init];
    multipleAdsOptions.numberOfAds = 1;
    
    GADNativeAdViewAdOptions *adViewOptions = [[GADNativeAdViewAdOptions alloc] init];
    adViewOptions.preferredAdChoicesPosition = GADAdChoicesPositionBottomLeftCorner;
    
    GADNativeAdMediaAdLoaderOptions *adLoaderOptions = [[GADNativeAdMediaAdLoaderOptions alloc] init];
    adLoaderOptions.mediaAspectRatio = GADMediaAspectRatioAny;
    
    GADVideoOptions *adVideoOptions = [[GADVideoOptions alloc] init];
    adVideoOptions.startMuted = YES;
    
    GADNativeMuteThisAdLoaderOptions *muteOptions = [GADNativeMuteThisAdLoaderOptions new];
    
    self.navIsLoading = YES;
    NSLog(@"原生广告:正在加载中");
    self.navLoadAd = [[GADAdLoader alloc] initWithAdUnitID:self.navADStr
                                               rootViewController:[UIApplication sharedApplication].keyWindow.rootViewController
                                                          adTypes:@[GADAdLoaderAdTypeNative]
                                                          options:@[multipleAdsOptions,
                                                                    adViewOptions,
                                                                    adLoaderOptions,
                                                                    adVideoOptions,
                                                                    muteOptions]];
    self.navLoadAd.delegate = self;
    [self.navLoadAd loadRequest:[GADRequest request]];

}

- (UIView *)setNavAdSuperView:(UIView *)spView {
    
    [self.nativeAdView removeFromSuperview];
    self.nativeAdView = [[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil]
        .firstObject;
        
    [self.nativeAdView setTranslatesAutoresizingMaskIntoConstraints:NO];

    [spView addSubview:self.nativeAdView];
    
    NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(_nativeAdView);
    [spView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_nativeAdView]|"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary]];
    [spView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_nativeAdView]|"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary]];
    
    return self.nativeAdView;
}

- (UIView *)setBigNavAdSuperView:(UIView *)spView {
    
    [self.nativeAdView removeFromSuperview];
    self.nativeAdView = [[NSBundle mainBundle] loadNibNamed:@"BigNativeAdView" owner:nil options:nil]
        .firstObject;
        
    [self.nativeAdView setTranslatesAutoresizingMaskIntoConstraints:NO];

    [spView addSubview:self.nativeAdView];
    
    NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(_nativeAdView);
    [spView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_nativeAdView]|"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary]];
    [spView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_nativeAdView]|"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary]];
    
    return self.nativeAdView;
}

- (void)navAD{

    GADNativeAdView *nativeAdView = self.nativeAdView;
    GADNativeAd *nativeAd = self.navAd;
    nativeAd.delegate = self;

    ((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;
    nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

    ((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
    nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;

    [((UIButton *)nativeAdView.callToActionView) setTitle:nativeAd.callToAction forState:UIControlStateNormal];
    nativeAdView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

    ((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
    nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;
    nativeAdView.iconView.layer.cornerRadius = 6;
    nativeAdView.iconView.layer.masksToBounds = YES;

    ((UILabel *)nativeAdView.storeView).text = nativeAd.store;
    nativeAdView.storeView.hidden = nativeAd.store ? NO : YES;

    ((UILabel *)nativeAdView.priceView).text = nativeAd.price;
    nativeAdView.priceView.hidden = nativeAd.price ? NO : YES;

    ((UILabel *)nativeAdView.advertiserView).text = nativeAd.advertiser;
    nativeAdView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

    nativeAdView.callToActionView.userInteractionEnabled = NO;

    nativeAdView.nativeAd = nativeAd;
    nativeAdView.layer.cornerRadius = 14;
    nativeAdView.layer.masksToBounds = YES;
}

- (void)showBigNavAd:(UIView *)view{
    if (self.navAd){
        [self setBigNavAdSuperView:view];
        [self navAD];
        
        __weak typeof(self) weakSelf = self;

        self.navAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
        
            NSString *currentIp = @"";
            NSArray *array = @[@"unkown", @"estimated", @"PublisherProvided", @"Precise"];
            
            double doubleValue = [value.value doubleValue];
            [[CSNetworkHelper standardInstance]postMoneyWithURL:@"http://healthhaha.com/app/adValues" CurrentIp:currentIp adid:weakSelf.navADStr adformat:@"nav" valueMicros:doubleValue * 1000 currencyCode:value.currencyCode precisionType:value.precision];
            
        };
        
        self.navAd = nil;
        NSLog(@"原生广告:展示");
    }else{
        NSLog(@"原生广告:没广告");
    }
    [self requestAllAd];
}

- (void)showNavAd:(UIView *)view{
    if (self.navAd){
        [self setNavAdSuperView:view];
        [self navAD];

        __weak typeof(self) weakSelf = self;

        self.navAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
        
            NSString *currentIp = @"";
            NSArray *array = @[@"unkown", @"estimated", @"PublisherProvided", @"Precise"];
            
            double doubleValue = [value.value doubleValue];
            [[CSNetworkHelper standardInstance]postMoneyWithURL:@"http://healthhaha.com/app/adValues" CurrentIp:currentIp adid:weakSelf.navADStr adformat:@"nav" valueMicros:doubleValue * 1000 currencyCode:value.currencyCode precisionType:value.precision];
            
        };
        
        self.navAd = nil;
        NSLog(@"原生广告:展示");
    }else{
        NSLog(@"原生广告:没广告");
    }
    [self requestAllAd];
}

- (BOOL)haveNavAd{
    if (self.navAd){
        return YES;
    }else{
        return NO;
    }
}

- (void)adLoader:(nonnull GADAdLoader *)adLoader didFailToReceiveAdWithError:(nonnull NSError *)error {
    self.navIsLoading = NO;
    NSLog(@"原生广告加载失败 %@", [error localizedDescription]);
}

- (void)adLoader:(nonnull GADAdLoader *)adLoader didReceiveNativeAd:(nonnull GADNativeAd *)nativeAd {
    self.navIsLoading = NO;
    NSLog(@"原生广告:请求成功");
    self.navAd = nativeAd;
}

- (void)requestAllAd{
    if (self.dataDict){
        [self getAdStr];
        [self requestOpenAd];
        [self requestInterAd];
        [self requestNavAd];
    }
}

- (void)requestOpenAd{
    
    if (self.openIsLoading){
        NSLog(@"开屏广告:正在加载中");
        return;;
    }
    
    if (self.openAd){
        NSLog(@"开屏广告:已经存在");
        return;
    }
    
    self.openIsLoading = YES;
    NSLog(@"开屏广告:正在加载中");

    [GADAppOpenAd loadWithAdUnitID:self.openADStr request:[GADRequest request] completionHandler:^(GADAppOpenAd * _Nullable ad, NSError * _Nullable error) {
        
        self.openIsLoading = NO;
        
        if (error){
            NSLog(@"开屏广告加载失败 %@", [error localizedDescription]);
            return;
        }
        NSLog(@"开屏广告:请求成功");
        self.openAd = ad;
        
    }];

}

- (BOOL)haveOpenAd{
    if (self.openAd){
        return YES;
    }else{
        return NO;
    }
}

- (void)showOpenAd{
    if (self.openAd){
        self.openAd.fullScreenContentDelegate = self;
        [self.openAd presentFromRootViewController:nil];
        
            
            __weak typeof(self) weakSelf = self;

            self.openAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
            
                NSString *currentIp = @"";
                NSArray *array = @[@"unkown", @"estimated", @"PublisherProvided", @"Precise"];
                
                double doubleValue = [value.value doubleValue];
                [[CSNetworkHelper standardInstance]postMoneyWithURL:@"http://healthhaha.com/app/adValues" CurrentIp:currentIp adid:weakSelf.openADStr adformat:@"open" valueMicros:doubleValue * 1000 currencyCode:value.currencyCode precisionType:value.precision];
                
            };

        
        NSLog(@"开屏广告:展示");
    }else{
        NSLog(@"开屏广告:没广告");
    }
    [self requestAllAd];
}

// interAd

- (BOOL)haveInterAd{
    if (self.interAd){
        return YES;
    }else{
        return NO;
    }
}

- (void)requestInterAd{
    
    if (self.interIsLoading){
        NSLog(@"插页广告:正在加载中");
        return;
    }
    
    if (self.interAd){
        NSLog(@"插页广告:已经存在");
        return;
    }
    
    self.interIsLoading = YES;
    NSLog(@"插页广告:正在加载中");

    [GADInterstitialAd loadWithAdUnitID:self.intADStr
                                request:[GADRequest request]
                      completionHandler:^(GADInterstitialAd *ad, NSError *error) {
        self.interIsLoading = NO;
        if (error) {
            NSLog(@"插页广告加载失败 %@", [error localizedDescription]);
            return;
        }
        NSLog(@"插页广告:请求成功");
        self.interAd = ad;
    }];
}

- (void)showInterAdWithVC:(UIViewController *)vc dismiss:(nullable void (^)(void))dismiss{
    
    if (self.showIntOrNav){
        
        __block void (^localDismiss)(void) = dismiss;

        if (self.navAd){
            CSFullNavVC *vc = [[CSFullNavVC alloc]init];
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            
            UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            UIView *view = [[UIView alloc] initWithFrame:nav.view.bounds];
            view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
            [[UIApplication sharedApplication].keyWindow addSubview:view];
            

            vc.closeBlock = ^{
                [view removeFromSuperview];
                [vc dismissViewControllerAnimated:NO completion:nil];
                localDismiss ? localDismiss() : nil;
                localDismiss = nil;
            };
            
            [nav presentViewController:vc animated:NO completion:nil];
        }else{
            dismiss ? dismiss() : nil;
            dismiss = nil;
            [self requestAllAd];
        }
        
    }else{
        if (self.interAd){
            self.interAd.fullScreenContentDelegate = self;
            [self.interAd presentFromRootViewController:nil];
            
            if (dismiss){
                self.interDismiss = dismiss;
            }
            
            __weak typeof(self) weakSelf = self;

            self.interAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
            
                NSString *decimalString = [value.value stringValue];

                NSString *currentIp = @"";
                NSArray *array = @[@"unkown", @"estimated", @"PublisherProvided", @"Precise"];
                
                double doubleValue = [value.value doubleValue];
                [[CSNetworkHelper standardInstance]postMoneyWithURL:@"http://healthhaha.com/app/adValues" CurrentIp:currentIp adid:weakSelf.intADStr adformat:@"int" valueMicros:doubleValue * 1000 currencyCode:value.currencyCode precisionType:value.precision];
                
            };
            
            NSLog(@"插页广告:展示");
        }else{
            NSLog(@"插页广告:没广告");
            dismiss ? dismiss() : nil;
            [self requestAllAd];
        }
    }
    

}

//- (void)showInterAd{
//
//    if (self.interAd){
//        self.interAd.fullScreenContentDelegate = self;
//        [self.interAd presentFromRootViewController:nil];
//        
//        if ([CSVpnManager standardInstance].providerManager.connection.status == NEVPNStatusConnected){
//            
//            __weak typeof(self) weakSelf = self;
//
//            self.interAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
//            
//                NSString *currentIp = [CSVpnManager standardInstance].currentData[@"vpsIp"];
//                NSArray *array = @[@"unkown", @"estimated", @"PublisherProvided", @"Precise"];
//                
//                double doubleValue = [value.value doubleValue];
//                [[CSNetworkHelper standardInstance]postMoneyWithURL:@"http://healthhaha.com/app/adValues" CurrentIp:currentIp adid:weakSelf.intADStr adformat:@"int" valueMicros:doubleValue * 1000 currencyCode:value.currencyCode precisionType:array[value.precision]];
//                
//            };
//        }
//        
//        NSLog(@"插页广告:展示");
//    }else{
//        NSLog(@"插页广告:没广告");
//    }
//    [self requestAllAd];
//}

- (void)ad:(nonnull id<GADFullScreenPresentingAd>)ad didFailToPresentFullScreenContentWithError:(nonnull NSError *)error {
    NSLog(@"Ad did fail to present full screen content.");
}

/// Tells the delegate that the ad will present full screen content.
- (void)adWillPresentFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
    NSLog(@"Ad will present full screen content.");
}

/// Tells the delegate that the ad dismissed full screen content.
- (void)adDidDismissFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
    
    if ([ad isKindOfClass:[GADInterstitialAd class]]){
        self.interAd = nil;
        [self requestAllAd];
        self.interDismiss ? self.interDismiss() : nil;
        self.interDismiss = ^(void){};
    }
    
    if ([ad isKindOfClass:[GADAppOpenAd class]]){
        self.openAd = nil;
        [self requestAllAd];
        self.openDismiss ? self.openDismiss() : nil;
    }
    
}


@end
